﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace DeepTime.BootStrapper.Utilities
{
    public class ImageExtensionBehaviours
    {
        #region Relative Source

        public static string GetRelativeSource(DependencyObject obj)
        {
            return (string)obj.GetValue(RelativeSourceProperty);
        }

        public static void SetRelativeSource(DependencyObject obj, string value)
        {
            obj.SetValue(RelativeSourceProperty, value);
        }

        // Using a DependencyProperty as the backing store for Validator.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RelativeSourceProperty =
            DependencyProperty.RegisterAttached("RelativeSource", typeof(string), typeof(ImageExtensionBehaviours), new PropertyMetadata("", new PropertyChangedCallback(RelativeSourcePropertyChangedCallback)));

        private static void RelativeSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Image ParentControl = d as Image;

            if (ParentControl == null)
            {
                return;
            }

            if (e.NewValue == null || e.NewValue.ToString() == string.Empty)
            {
                return;
            }

            ParentControl.ImageOpened -= ParentControl_ImageOpened;
            ParentControl.ImageOpened += ParentControl_ImageOpened;

            string baseURL = new Uri(App.Current.Host.Source, "../").OriginalString;
            ParentControl.Source = new BitmapImage(new Uri(baseURL + e.NewValue.ToString()));
        }

        #endregion Relative Source

        #region Image Event Handlers

        private static void ParentControl_ImageOpened(object sender, RoutedEventArgs e)
        {
            Image img = sender as Image;

            if (img != null)
            {
                img.InvalidateArrange();
                img.InvalidateMeasure();
            }
        }

        #endregion Image Event Handlers       
    }
}
